//
//  YXSearchServersListViewController.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/6/22.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "YXSearchServersListViewController.h"
#import "IFlyMSC/IFlyMSC.h"
#import "IATConfig.h"
#import "ISRDataHelper.h"
#import "SCGIFImageView.h"
#import "YXSerachServerTableViewCell.h"
#import "YXSerachServerModel.h"
#import "DetailMakeSureViewController.h"
#import <AVFoundation/AVSpeechSynthesis.h>
//需要实现IFlyRecognizerViewDelegate识别协议
@interface YXSearchServersListViewController ()<IFlySpeechRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,AVSpeechSynthesizerDelegate>
{
    AVSpeechSynthesizer *_avSpeaker;
}
//不带界面的识别对象
@property (nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;
@property (nonatomic, strong) NSString * result;
@property (nonatomic, strong) UIButton * backBtn;
@property (nonatomic, strong) UILabel *sayValueLabel; // 说的语音 字符串
@property (nonatomic, strong) UILabel *backValueLabel;// 返回的提示语

@property (nonatomic, strong) UITableView *mainTableView; // 主框架
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UILabel *typeNmaeLabel; // 搜索出来的类型 标题
@property (nonatomic, strong) YXSerachServerModel *serachServerModel; //数据源.item
@property (nonatomic, strong) NSMutableArray *datamuArray;
@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) AVSpeechUtterance *utterance;// 正在读音的对象
@property (nonatomic, strong) SCGIFImageView *hBottomgifImageView;
@property (nonatomic, strong) SCGIFImageView *BottomgifImageView;
@end

@implementation YXSearchServersListViewController
- (void)serachInfoMation {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=search" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"keywords":self.sayValueLabel.text,@"lat":[UserModel sharedInstanced].latitude,@"lnt":[UserModel sharedInstanced].longitude} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
//            ShowMessage(@"操作成功");
            self.serachServerModel = [YXSerachServerModel yy_modelWithDictionary:responseObject[@"data"]];
            [self.datamuArray removeAllObjects];
            [self.datamuArray addObjectsFromArray:self.serachServerModel.item];
            if (self.datamuArray.count > 0) {
                self.mainTableView.hidden = NO;
            }else{
                self.mainTableView.hidden = YES;
            }
            [self boFangTextWithString:self.serachServerModel.reponse]; // 语音播放
            self.backValueLabel.text = self.serachServerModel.reponse;
            self.typeNmaeLabel.text = [NSString stringWithFormat:@"    %@",self.serachServerModel.listtitle];
            [self.mainTableView reloadData];
        }else{
            ShowMessage(@"用户名或密码错误");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
// 文本读语音方法 stra是要读的文本
- (void)boFangTextWithString:(NSString *)stra
{
    //初始化语音合成器
    _avSpeaker = [[AVSpeechSynthesizer alloc] init];
    _avSpeaker.delegate = self;
    //初始化要说出的内容
    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:stra];
    //设置语速,语速介于AVSpeechUtteranceMaximumSpeechRate和AVSpeechUtteranceMinimumSpeechRate之间
    //AVSpeechUtteranceMaximumSpeechRate
    //AVSpeechUtteranceMinimumSpeechRate
    //AVSpeechUtteranceDefaultSpeechRate
    utterance.rate = 0.5;
    
    //设置音高,[0.5 - 2] 默认 = 1
    //AVSpeechUtteranceMaximumSpeechRate
    //AVSpeechUtteranceMinimumSpeechRate
    //AVSpeechUtteranceDefaultSpeechRate
    utterance.pitchMultiplier = 1;
    
    //设置音量,[0-1] 默认 = 1
    utterance.volume = 1;
    
    //读一段前的停顿时间
    utterance.preUtteranceDelay = 0.5;
    //读完一段后的停顿时间
    utterance.postUtteranceDelay = 0.5;
    
    //设置声音,是AVSpeechSynthesisVoice对象
    //AVSpeechSynthesisVoice定义了一系列的声音, 主要是不同的语言和地区.
    //voiceWithLanguage: 根据制定的语言, 获得一个声音.
    //speechVoices: 获得当前设备支持的声音
    //currentLanguageCode: 获得当前声音的语言字符串, 比如”ZH-cn”
    //language: 获得当前的语言
    //通过特定的语言获得声音 zh-HK   zh-CN
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    //通过voicce标示获得声音
    //AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithIdentifier:AVSpeechSynthesisVoiceIdentifierAlex];
    utterance.voice = voice;
    self.utterance = utterance;
    //开始朗读
    [_avSpeaker speakUtterance:utterance];
    
}
#pragma mark - AVSpeechSynthesizerDelegate
//已经开始
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
    
    
}
//已经说完
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
    
    //如果朗读要循环朗读，可以在这里再次调用朗读方法
    //[_avSpeaker speakUtterance:utterance];
}
//已经暂停
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance{
    
}
//已经继续说话
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance{
    
}
//已经取消说话
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance{
    
}
//将要说某段话
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance{
    
}


- (void)backBtnAction:(UIButton *)btn
{
    // CATransition动画实现
    [self pushWithAnimationType:@"fade"];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.mainTableView.hidden = YES;
    // 背景图
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,HEIGHT_6S_SCALE)];
//    bgImageView.backgroundColor = [UIColor clearColor];
    bgImageView.image = [UIImage imageNamed:@"backimg"];
    [self.view addSubview:bgImageView];
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"runDownUpB.gif" ofType:nil];
    NSData* imageData = [NSData dataWithContentsOfFile:filePath];
    SCGIFImageView* gifImageView = [[SCGIFImageView alloc] initWithFrame:CGRectMake(0,SCREEN_HEIGHT * 0.5 - 70,SCREEN_WIDTH,77)];
    [gifImageView setData:imageData];
    [self.view addSubview:gifImageView];
    
    NSString *filePathBottom2 = [[NSBundle mainBundle] pathForResource:@"runDownUpS.gif" ofType:nil];
    NSData *imageDataBottom2 = [NSData dataWithContentsOfFile:filePathBottom2];
    SCGIFImageView *hBottomgifImageView = [[SCGIFImageView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - SafeAreaBottomHeight - 100 / HEIGHT_6S_SCALE,SCREEN_WIDTH, 50 / HEIGHT_6S_SCALE)];
    self.hBottomgifImageView = hBottomgifImageView;
    [hBottomgifImageView setData:imageDataBottom2];
    [self.view addSubview:hBottomgifImageView];
    hBottomgifImageView.hidden = YES;
    
    NSString* filePathBottom = [[NSBundle mainBundle] pathForResource:@"yuyin.gif" ofType:nil];
    NSData* imageDataBottom = [NSData dataWithContentsOfFile:filePathBottom];
    SCGIFImageView* BottomgifImageView = [[SCGIFImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 32 / WIDTH_6S_SCALE, SCREEN_HEIGHT - SafeAreaBottomHeight - 100 / HEIGHT_6S_SCALE, 65 / WIDTH_6S_SCALE, 65 / WIDTH_6S_SCALE)];
    BottomgifImageView.userInteractionEnabled = YES;
    [BottomgifImageView setData:imageDataBottom];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapAction:)];
    longPress.minimumPressDuration = 0.2; //定义按的时间
    longPress.numberOfTouchesRequired = 1;
    [BottomgifImageView addGestureRecognizer:longPress];
    self.BottomgifImageView = BottomgifImageView;
    [self.view addSubview:BottomgifImageView];
    
    UILabel *sayValueLabel = [[UILabel alloc]initWithFrame:CGRectMake(10 / WIDTH_6S_SCALE, STATUS_HEIGHT + 20 / HEIGHT_6S_SCALE, SCREEN_WIDTH - 20, 20 / HEIGHT_6S_SCALE)];
    sayValueLabel.backgroundColor = [UIColor clearColor];
    sayValueLabel.textColor = getColor(whiteColor);
    sayValueLabel.textAlignment = NSTextAlignmentRight;
    sayValueLabel.font = DEF_FontSize_16;
    sayValueLabel.numberOfLines = 0;
//    sayValueLabel.text = @"你好啊的电视里健身房";
    self.sayValueLabel = sayValueLabel;
    [self.view addSubview:sayValueLabel];
    
    UILabel *backValueLabel = [[UILabel alloc]initWithFrame:CGRectMake(15 / WIDTH_6S_SCALE, CGRectGetMaxY(sayValueLabel.frame) + 10 / HEIGHT_6S_SCALE, SCREEN_WIDTH - 30 / WIDTH_6S_SCALE, 20 / HEIGHT_6S_SCALE)];
    backValueLabel.backgroundColor = [UIColor clearColor];
    backValueLabel.textColor = getColor(whiteColor);
    backValueLabel.textAlignment = NSTextAlignmentLeft;
    backValueLabel.font = DEF_FontSize_16;
    backValueLabel.numberOfLines = 0;
//    backValueLabel.text = @"好的，我找到以下信息：";
    self.backValueLabel = backValueLabel;
    [self.view addSubview:backValueLabel];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(10 / WIDTH_6S_SCALE, 0, SCREEN_WIDTH - 20 / WIDTH_6S_SCALE, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight)];
    self.bgView = bgView;
//    bgView.backgroundColor = getColor(@"CEC9D5");
    bgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgView];
    __weak typeof(self)weakself = self;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backValueLabel.mas_bottom).offset(20 / HEIGHT_6S_SCALE);
        make.left.equalTo(weakself.view.mas_left).offset(10 / WIDTH_6S_SCALE);
        make.right.equalTo(weakself.view.mas_right).offset(-10 / WIDTH_6S_SCALE);
        make.bottom.equalTo(BottomgifImageView.mas_top).offset(-20 / HEIGHT_6S_SCALE);
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight  cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = bgView.bounds;
        maskLayer.path = maskPath.CGPath;
        bgView.layer.mask = maskLayer;
    }];
    
    [bgView addSubview:self.mainTableView];
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(bgView);
    }];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, STATUS_HEIGHT + 10, 30, 30)];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"WechatIMG235"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}
// 图片手势  长按图片的时候 启动识别语音功能
- (void) longTapAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        self.hBottomgifImageView.hidden = NO;
        NSLog(@"long pressTap state :begin");
        //停止朗读
        [_avSpeaker stopSpeakingAtBoundary:self.utterance];// 停止上一次还没说完的话
        
        _sayValueLabel.text = @"";
        //创建语音识别对象
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        _iFlySpeechRecognizer.delegate = self;
        //设置识别参数
        //设置为听写模式
        [_iFlySpeechRecognizer setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
        //asr_audio_path 是录音文件名，设置value为nil或者为空取消保存，默认保存目录在Library/cache下。
        [_iFlySpeechRecognizer setParameter:@"iat.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        //启动识别服务
        [_iFlySpeechRecognizer startListening];
    }
    if (longPress.state == UIGestureRecognizerStateEnded) {
         NSLog(@"long pressTap state :end");
        self.hBottomgifImageView.hidden = YES;
        [_iFlySpeechRecognizer stopListening];
    }
}

#pragma -mark  IFlySpeechRecognizerDelegate协议实现
//识别结果返回代理
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    _result =[NSString stringWithFormat:@"%@%@", _sayValueLabel.text,resultString];
    
    NSString * resultFromJson =  nil;
    
    if([IATConfig sharedInstance].isTranslate){
        
        NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:    //The result type must be utf8, otherwise an unknown error will happen.
                                    [resultString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        if(resultDic != nil){
            NSDictionary *trans_result = [resultDic objectForKey:@"trans_result"];
            
            if([[IATConfig sharedInstance].language isEqualToString:@"en_us"]){
                NSString *dst = [trans_result objectForKey:@"dst"];
                NSLog(@"dst=%@",dst);
                resultFromJson = [NSString stringWithFormat:@"%@\ndst:%@",resultString,dst];
            }
            else{
                NSString *src = [trans_result objectForKey:@"src"];
                NSLog(@"src=%@",src);
                resultFromJson = [NSString stringWithFormat:@"%@\nsrc:%@",resultString,src];
            }
        }
    }
    else{
        resultFromJson = [ISRDataHelper stringFromJson:resultString];
    }
//    NSString *str = @"my name is jiemu";
    
//    1.从第三个字符开始，截取长度为4的字符串
//    NSString *str2 = [str substringWithRange:NSMakeRange(3,4)];//str2 = "name"
    if (results == nil || results == NULL) {
        return;
    }
    _sayValueLabel.text = [NSString stringWithFormat:@"%@%@", _sayValueLabel.text,resultFromJson];
    // 截取字符串 去掉最后的句号
//    NSString *clStr = _sayValueLabel.text;
//
//    if (clStr !=nil & clStr != NULL) {
//        if (clStr.length > 0) {
//            NSString *lastStr = [clStr substringFromIndex:clStr.length - 1];
//            NSString *resultStr;
//            if ([lastStr isEqualToString:@"。"]) {
//                resultStr = [clStr substringWithRange:NSMakeRange(0,clStr.length - 1)];
//            }else{
//                resultStr = clStr;
//            }
//            _sayValueLabel.text = resultStr;
//        }
//    }
    
    if (isLast){
        NSLog(@"ISR Results(json)：%@",  self.result);
    }
    NSLog(@"_result=%@",_result);
    NSLog(@"resultFromJson=%@",resultFromJson);
    NSLog(@"isLast=%d,_textView.text=%@",isLast,_sayValueLabel.text);
    NSString *stra = _sayValueLabel.text;
    if (stra.length <= 0 || stra == nil || stra == NULL) {
//        ShowMessage(@"请语音录入收索内容");
        return;
    }
    [self serachInfoMation];
}
//识别会话结束返回代理
- (void)onCompleted: (IFlySpeechError *) error{}
//停止录音回调
- (void) onEndOfSpeech{}
//开始录音回调
- (void) onBeginOfSpeech{}
//音量回调函数
- (void) onVolumeChanged: (int)volume{}
//会话取消回调
- (void) onCancel{}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datamuArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YXSerachServerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YXSerachServerTableViewCell class])];
    cell.serverModellList = (ServerModellList *)self.datamuArray[indexPath.row];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailMakeSureViewController *VC = [[DetailMakeSureViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:VC];
    VC.serverModellList = (ServerModellList *)self.datamuArray[indexPath.row];
    VC.typeStrXq = @"2";
//    [self.navigationController pushViewController:VC animated:NO];
    [self presentViewController:nav animated:NO completion:nil];
}
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
#pragma mark - init
- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(10 / WIDTH_6S_SCALE, 0, SCREEN_WIDTH - 20 / WIDTH_6S_SCALE, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _mainTableView.backgroundColor = getColor(@"CEC9D5");
        _mainTableView.tableHeaderView = self.headerView;
        _mainTableView.tableFooterView = self.footerView;
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;
        _mainTableView.bounces = NO;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 动态行高
        _mainTableView.rowHeight = UITableViewAutomaticDimension;
        // 预估行高
        _mainTableView.estimatedRowHeight = 80;
        
        [_mainTableView registerClass:[YXSerachServerTableViewCell class] forCellReuseIdentifier:NSStringFromClass([YXSerachServerTableViewCell class])];
    }
    return _mainTableView;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40 / HEIGHT_6S_SCALE)];
        _headerView.backgroundColor = [UIColor grayColor];
        
        UILabel *typeNmaeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _headerView.frame.size.width, _headerView.frame.size.height)];
        typeNmaeLabel.backgroundColor = getColor(@"B4B0C0");
        typeNmaeLabel.textColor = getColor(blackColor);
        typeNmaeLabel.font = DEF_FontSize_14;
        typeNmaeLabel.textAlignment = NSTextAlignmentLeft;
//        typeNmaeLabel.text = @"   下水道维修工人(20个)";
        self.typeNmaeLabel = typeNmaeLabel;
        [_headerView addSubview:typeNmaeLabel];
    }
    return _headerView;
}
- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}
- (NSMutableArray *)datamuArray
{
    if (!_datamuArray) {
        _datamuArray = @[].mutableCopy;
    }
    return _datamuArray;
}
@end
